public class Solution {
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int closest = Integer.MAX_VALUE / 2;
        for(int i = 0; i < nums.length - 2; i++) {
            int start = i + 1;
            int end = nums.length - 1;
            while(start < end) {
                int t = nums[start] + nums[end] + nums[i];
                if(t > target) {
                    end--;
                } else if(t < target) {
                    start++;
                } else {
                    return target;
                }
                if(Math.abs(target - t) < Math.abs(target - closest)) {
                    closest = t;
                }
            }
        }
        return closest;
    }
}
